/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package 解析.node.node;
 
import 解析.node.others.TreeInfo;
import 解析.Matcher;

/**
 *
 * @author yanxi
 */
public class Branch extends Node { 
    public Node[] atoms = new Node[2];
    public int size = 2;
    public Node conn; 

    public Branch(Node first, Node second, Node branchConn) {
        conn = branchConn;
        atoms[0] = first;
        atoms[1] = second;
        
        getChildren().add(atoms[0]);
        getChildren().add(atoms[1]);
        getChildren().add(conn);  
    }
    
    public void add(Node node) {
        if (size >= atoms.length) {
            Node[] tmp = new Node[atoms.length * 2];
            System.arraycopy(atoms, 0, tmp, 0, atoms.length);
            atoms = tmp; 
        }
        atoms[size++] = node; 
        getChildren().add(node); 
    }

    @Override
    public boolean match(Matcher matcher, int i, CharSequence seq) {
        for (int n = 0; n < size; n++) {
            if (atoms[n] == null) {
                if (conn.next.match(matcher, i, seq)) {
                    return true;
                }
            } else if (atoms[n].match(matcher, i, seq)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean study(TreeInfo info) {
        int minL = info.minLength;
        int maxL = info.maxLength;
        boolean maxV = info.maxValid;

        int minL2 = Integer.MAX_VALUE; //arbitrary large enough num
        int maxL2 = -1;
        for (int n = 0; n < size; n++) {
            info.reset();
            if (atoms[n] != null) {
                atoms[n].study(info);
            }
            minL2 = Math.min(minL2, info.minLength);
            maxL2 = Math.max(maxL2, info.maxLength);
            maxV = (maxV & info.maxValid);
        }

        minL += minL2;
        maxL += maxL2;

        info.reset();
        conn.next.study(info);

        info.minLength += minL;
        info.maxLength += maxL;
        info.maxValid &= maxV;
        info.deterministic = false;
        return false;
    } 
}
